package org.lanqiao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.lanqiao.dao.ActivityDao;
import org.lanqiao.entity.AcActivity;
import org.lanqiao.entity.Activity;
import org.lanqiao.mapper.ActivityMapper;
import org.lanqiao.service.ActivityService;
import org.lanqiao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author andenj
 * @describe
 * @data
 */
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    ActivityDao activityDao;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    private JmsMessagingTemplate jmsTemplate;
    /**
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/6/12 10:20
     * @Param [localIp]
     * @explain   查询距离最近的几个活动
     * @return java.util.List<org.lanqiao.entity.Activity>
     */

    @Override
    public List<Activity> getAllsite(String  localIp) {
        //所有地址的集合
        List<Activity> allSite = activityDao.getAllSite();
        //所有活动的集合
        List<Activity>activities=new ArrayList<>();
        //距离和活动id
        Map<String,Double>map = new HashMap<>();
        for (int i = 0; i <allSite.size() ; i++) {
            String ips = LatitudeUtils.getGeocoderLatitude(allSite.get(i).getActivitySite());

            double[] ip1 = LatitudeUtils.std(ips);
            double[] ip2 = LatitudeUtils.std(localIp);

            //查出两个点的距离
            Double distance = LatitudeUtils.getDistance(ip1[0], ip1[1], ip2[0], ip2[1]);
            map.put(allSite.get(i).getActivityId(),distance);
        }
        //把获取到的距离和活动id放进map中  然后比较 ，然后排序 拿到最小的几个值
        Map<String, Double> doubleMap = LatitudeUtils.sortByValue(map);
        Set<String> strings = doubleMap.keySet();
        for (String str:strings){
            Activity activity = activityDao.getActivityById(str);
           activities.add(activity);
        }

        List<Activity> list=new ArrayList<>();
        for (int i = 0; i <3 ; i++) {
            list.add(activities.get(i));
        }
        return list;
    }

    @Override
    public String  getMap(String ip) {
        String address=null;
        try {
            address = BaiDuMapUtil.getAddress(ip);
        } catch (IOException e) {
            e.printStackTrace();
            return "获取不到地址呢";
        }
        return address;
    }


    /**
     * 功能描述 通过userId查询活动并分页、返回参数
     *
     * @return java.util.List<org.lanqiao.entity.Activity>
     * @author 吴奇
     * @date 2019/5/22
     */
    @Override



    public PageInfo<AcActivity> listGetActivity(String userEmail,String name, int currentPage) {
        //在使用pageHelper插件在查询之前只需调用，startPage，传入页码currentPage，设置数据显示多少
        PageHelper.startPage(currentPage, 3);
        List<AcActivity> ac = activityDao.getActivity(userEmail,name);
        //PageInfo把ac数据进行分页
        PageInfo<AcActivity> pageInfo = new PageInfo<>(ac);
        return pageInfo;
    }

    /**
     * @return org.lanqiao.util.Result
     * @Author 刘金渝
     * @Description //TODO
     * @Date 2019/5/27 17:09
     * @Param [activity]
     * @explain
     */

    @Override
    public Result addActivity(Activity activity) {
        try {
            activityDao.addActivity(activity);
        } catch (Exception e) {
            return Result.defeated("");
        }
        return Result.ok("成功的创建了一个活动");
    }


    @Override
    public List<Map> getAllActivity() {
        List list = (List) redisTemplate.opsForValue().get("all-activity");
        System.out.println(list);
        if (list == null || list.size() == 0) {
            list = activityMapper.getAllActivity();
            jmsTemplate.convertAndSend(StringUtil.activity_query_queue, JSON.toJSONString(list));
            return list;
        } else {
            return list;
        }
    }


    @Override
    public void updateAct(String id) {
        //先修改在发消息
        activityMapper.updateAct(id);
        jmsTemplate.convertAndSend(StringUtil.activity_queue, id);
    }

    @Override
    public List<Map> getByNameActivity(String username) {

        return activityDao.getByNameActivity(username);

    }

    /**
     * @Author 王宇
     * @Description //TODO 根据活动名来进行活动的模糊查询
     * @Date 2019/06/03 16:13
     * @Param [activityName]
     * @return org.lanqiao.util.Result
     */

        @Override
    public Result getActivityName(String activityName) {
        Result result = new Result();
        Pattern pattern = Pattern.compile("^[a-zA-Z0-9\u4E00-\u9FA5]+$");
        Matcher matcher = pattern.matcher(activityName);
        boolean b = matcher.matches();
        try {
            List<Activity> activityNames = activityDao.getActivityName(activityName);
            if(activityNames.size()!=0&&b == true){
                result.setCode(0);
                result.setMsg("OK");
                result.setData(activityNames);
            }else{
                result.setCode(1);
                result.setMsg("该活动不存在");
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Author 彭泳寒
     * @Description //TODO 根据活动id来进行活动时间查询
     */
    @Override
    public Activity getActivityTime(String activityId) {
           return activityDao.getActivityTime(activityId);

    }

    /**
     *功能描述 修改活动
     * @author 吴奇
     * @date 2019/6/11
     * @return void
     */
    @Override
    public void updateAc(String id, String name, String sndtime) {
        activityDao.updateAc(id,name,sndtime);
    }

    @Override
    public Activity getActivityById(String activityId) {
        return activityDao.getActivityById(activityId);
    }

    /**
     *更具活动的id进行查询活动状态
     * @param activityId
     * @return 任春旭
     */
    public Activity queryStatus(String activityId){
        Activity activity = activityDao.queryStatus(activityId);
        return activity;
    }

    @Override
    public List<Map> getGiftsByUser(String wxId, String activityId) {
        Object o = redisTemplate.opsForValue().get(StringUtil.activity_gift);
        List list;
        if(o!=null){
            list = JSONObject.parseArray(o.toString(),String.class);
            return list;
        }else{
            list = activityMapper.getGiftsByUser(wxId,activityId);
            jmsTemplate.convertAndSend(StringUtil.activity_gift, JSON.toJSONString(list));
            return list;
        }
    }
}
